﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;

namespace KasaTakip
{
    public partial class frmKasaAlimi : XtraForm
    {
        private string MagazaNo = Program.AktifDepoNo.ToString();
        public DateTime IslemTarihi { get; set; }

        public frmKasaAlimi()
        {
            InitializeComponent();
            this.KeyPreview = true;
            gridNakitDetay.CellEndEdit += new DataGridViewCellEventHandler(gridNakitDetay_CellEndEdit);
            this.KeyDown += new KeyEventHandler(frmKasaAlimi_KeyDown);
        }

        void frmKasaAlimi_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.Control && e.KeyCode == Keys.Tab)
            //{
            //    if (xtraTabControl1.TabPages.Count - 1 == xtraTabControl1.SelectedTabPageIndex)
            //        xtraTabControl1.SelectedTabPageIndex = 0;
            //    else
            //        xtraTabControl1.SelectedTabPageIndex += 1;

            //    xtraTabControl1.SelectedTabPage.Focus();

            //    e.Handled = true;
            //    e.SuppressKeyPress = true;
            //}
        }

        Database OffDb = Program.Db;
        int ClosureID = 0;

        private void frmKasaAlimi_Load(object sender, EventArgs e)
        {
            if (Program.AdminMode)
            {
                toolStripButton2.Visible = true;
               
            }

            gridHarcamalar.Enabled = true;
            grdMasrafFaturalari.Enabled = true;

            label16.Text = IslemTarihi.ToShortDateString();
            this.Icon = Properties.Resources.ikon;
            foreach (var item in OffDb.Kasalar)
            {
                cmbKasa.Items.Add(item);
            }

            foreach (var item in OffDb.Kasiyerler.Where(x => x.Aktif == true))
            {
                cmbKasiyer.Items.Add(item);
            }
        }

        //ok
        private void NakitDetaylariYukle(Database db)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Para Cinsi", typeof(string));
            dt.Columns.Add("Carpan", typeof(double));
            dt.Columns.Add("Adet", typeof(int));
            dt.Columns.Add("Tutar", typeof(double));

            foreach (var item in OffDb.ParaBirimleri)
            {
                var detay = db.NakitDetaylari.Where(x => x.ParaCinsi == item.ParaCinsi).FirstOrDefault();
                if (detay != null)
                {
                    dt.Rows.Add(item.ParaCinsi, item.Carpan, detay.Miktar, detay.Tutar);
                }
                else
                {
                    dt.Rows.Add(item.ParaCinsi, item.Carpan, 0, 0);
                }
            }

            gridNakitDetay.DataSource = dt;
            gridNakitDetay.Columns["Carpan"].Visible = false;
            gridNakitDetay.Refresh();
        }

        //ok
        private void BankaHareketleriYukle(Database db)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Banka Adı", typeof(string));
            dt.Columns.Add("Tutar", typeof(double));
            dt.Columns.Add("Slip", typeof(int));

            foreach (var item in OffDb.Bankalar)
            {
                var hr = db.BankaHareketleri.Where(x => x.BankaID == item.ID).FirstOrDefault();
                if (hr != null)
                {
                    dt.Rows.Add(item.ID, item.Aciklama, hr.Tutar, hr.Slip);
                }
                else
                {
                    dt.Rows.Add(item.ID, item.Aciklama, 0, 0);
                }
            }

            gridKrediDetay.DataSource = dt;
            gridKrediDetay.Columns[0].Visible = false;
            gridKrediDetay.Columns[1].ReadOnly = true;
        }

        //ok
        private void AcikHesapHareketleriYukle(Database db)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CariID", typeof(int));
            dt.Columns.Add("Kdv Dahil Tutar", typeof(double));
            dt.Columns.Add("KdvTutar", typeof(double));
            dt.Columns.Add("BelgeNo", typeof(string));
            gridAcikHesap.AutoGenerateColumns = false;

            foreach (var item in db.AcikHesapHareketleri.Where(x => x.ClosureID == ClosureID))
            {
                dt.Rows.Add(item.CariID, item.KdvDahilTutar, item.KdvHaricTutar, item.BelgeNo);
            }

            for (int i = 0; i < 5; i++)
            {
                dt.Rows.Add();
            }

            DataGridViewComboBoxColumn col = gridAcikHesap.Columns[0] as DataGridViewComboBoxColumn;
            col.ValueType = typeof(int);
            col.DataSource = OffDb.Cariler.Where(x => x.MagazaNo == Program.AktifDepoNo).ToList();
            col.ValueMember = "ID";
            col.DisplayMember = "Unvani";

            gridAcikHesap.Columns[0].DataPropertyName = "CariID";
            gridAcikHesap.Columns[1].DataPropertyName = "Kdv Dahil Tutar";
            gridAcikHesap.Columns[2].DataPropertyName = "KdvTutar";
            gridAcikHesap.Columns[3].DataPropertyName = "BelgeNo";
            gridAcikHesap.DataSource = dt;

        }

        //ok
        private void MasrafHareketleriYukle(Database db)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Aciklama", typeof(string));
            dt.Columns.Add("Tutar", typeof(decimal));

            foreach (var item in db.MasrafHareketleri.Where(x => x.ClosureID == ClosureID))
            {
                dt.Rows.Add(item.Aciklama, item.Tutar);
            }

            for (int i = 0; i < 5; i++)
            {
                dt.Rows.Add();
            }

            gridHarcamalar.DataSource = dt;
        }

        //ok
        private void CariHesapTahsilatlariYukle(Database db)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CariID", typeof(int));
            dt.Columns.Add("Tip", typeof(int));
            dt.Columns.Add("BankaID", typeof(int));
            dt.Columns.Add("Tutar", typeof(double));
            dt.Columns.Add("CekNo", typeof(string));

            gridCariTahsilat.AutoGenerateColumns = false;

            foreach (var item in db.CariTahsilatHareketleri.Where(x => x.ClosureID == ClosureID))
            {
                dt.Rows.Add(item.CariID, item.Tip, item.BankaID, item.Tutar, item.CekNo);
            }

            for (int i = 0; i < 5; i++)
            {
                dt.Rows.Add();
            }

            DataGridViewComboBoxColumn cari = gridCariTahsilat.Columns[0] as DataGridViewComboBoxColumn;
            cari.ValueType = typeof(int);
            cari.DataSource = OffDb.Cariler;
            cari.ValueMember = "ID";
            cari.DisplayMember = "Unvani";
            DataGridViewComboBoxColumn tip = gridCariTahsilat.Columns[1] as DataGridViewComboBoxColumn;
            tip.Items.Add(new ComboItem() { Text = "Kredi Kartı", ID = 0 });
            tip.Items.Add(new ComboItem() { Text = "Çek", ID = 1 });
            tip.Items.Add(new ComboItem() { Text = "Nakit", ID = 2 });
            tip.ValueType = typeof(int);
            tip.DisplayMember = "Text";
            tip.ValueMember = "ID";
            DataGridViewComboBoxColumn bnk = gridCariTahsilat.Columns[2] as DataGridViewComboBoxColumn;
            bnk.ValueType = typeof(int);
            bnk.DataSource = OffDb.Bankalar;
            bnk.ValueMember = "ID";
            bnk.DisplayMember = "Aciklama";

            gridCariTahsilat.Columns[0].DataPropertyName = "CariID";
            gridCariTahsilat.Columns[1].DataPropertyName = "Tip";
            gridCariTahsilat.Columns[2].DataPropertyName = "BankaID";
            gridCariTahsilat.Columns[3].DataPropertyName = "Tutar";
            gridCariTahsilat.Columns[4].DataPropertyName = "CekNo";
            gridCariTahsilat.DataSource = dt;
        }

        //ok
        private void MasrafFaturalariYukle(Database db)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CariID", typeof(int));
            dt.Columns.Add("MasrafID", typeof(int));
            dt.Columns.Add("Adet", typeof(double));
            dt.Columns.Add("Tutar", typeof(double));

            grdMasrafFaturalari.AutoGenerateColumns = false;

            foreach (var item in db.MasrafFaturalari.Where(x => x.ClosureID == ClosureID))
            {
                dt.Rows.Add(item.CariID, item.MasrafID, item.Miktar, item.Tutar);
            }

            for (int i = 0; i < 5; i++)
            {
                dt.Rows.Add();
            }

            DataGridViewComboBoxColumn cari = grdMasrafFaturalari.Columns[0] as DataGridViewComboBoxColumn;
            cari.ValueType = typeof(int);
            cari.DataSource = OffDb.Cariler;
            cari.ValueMember = "ID";
            cari.DisplayMember = "Unvani";

            DataGridViewComboBoxColumn bnk = grdMasrafFaturalari.Columns[1] as DataGridViewComboBoxColumn;
            bnk.ValueType = typeof(int);
            bnk.DataSource = OffDb.MasrafKartlari;
            bnk.ValueMember = "ID";
            bnk.DisplayMember = "Adi";

            grdMasrafFaturalari.Columns[0].DataPropertyName = "CariID";
            grdMasrafFaturalari.Columns[1].DataPropertyName = "MasrafID";
            grdMasrafFaturalari.Columns[2].DataPropertyName = "Adet";
            grdMasrafFaturalari.Columns[3].DataPropertyName = "Tutar";
            grdMasrafFaturalari.DataSource = dt;
        }

        //ok
        private void ZraporHareketYukle(Database db)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ZNo", typeof(string));
            dt.Columns.Add("Ciro", typeof(double));
            dt.Columns.Add("Fiş Adedi", typeof(double));
            dt.Columns.Add("Fatura Tutarı", typeof(double));
            dt.Columns.Add("Fatura Adedi", typeof(double));
            dt.Columns.Add("İade Tutarı", typeof(double));
            dt.Columns.Add("İade Adedi", typeof(double));
            dt.Columns.Add("İndirim Tutarı", typeof(double));

            foreach (var item in db.ZRaporlari.Where(x => x.ClosureID == ClosureID))
            {
                dt.Rows.Add(item.ZNo, item.ZTutari, item.FisAdedi, item.FaturaTutari, item.FaturaAdedi, item.IadeTutari, item.IadeAdedi, item.IndirimTutari);
            }

            gridZraporlari.DataSource = dt;
        }

        /// <summary>
        /// datayı sqlden okur yoksa offline db ye bakar
        /// </summary>
        /// <returns></returns>
        private Database ReadData()
        {
            Database Db = new Database();
            Kasa kasa = (Kasa)cmbKasa.SelectedItem;
            Kasiyer kasiyer = (Kasiyer)cmbKasiyer.SelectedItem;
            DateTime tarih = IslemTarihi.ToSmallDate();
            try
            {
                using (KasaEntity ent = new KasaEntity())
                {
                    var cl = ent.KasaKapanislari.Where(x => x.KasaID == kasa.ID && x.KasiyerID == kasiyer.ID && x.Tarih == tarih).FirstOrDefault();
                    if (cl != null)
                    {
                        ClosureID = cl.ID;
                        Db.Closures.Add(cl);
                        Db.AcikHesapHareketleri.AddRange(ent.AcikHesapHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                        Db.BankaHareketleri.AddRange(ent.BankaHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                        Db.CariTahsilatHareketleri.AddRange(ent.CariTahsilatHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                        Db.MasrafFaturalari.AddRange(ent.MasrafFaturalari.Where(x => x.ClosureID == cl.ID).ToList());
                        Db.MasrafHareketleri.AddRange(ent.MasrafHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                        Db.NakitDetaylari.AddRange(ent.NakitHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                        Db.ZRaporlari.AddRange(ent.ZRaporlari.Where(x => x.ClosureID == cl.ID).ToList());
                    }
                    else
                    {
                        cl = OffDb.Closures.Where(x => x.KasaID == kasa.ID && x.KasiyerID == kasiyer.ID && x.Tarih == tarih).FirstOrDefault();
                        if (cl != null)
                        {
                            ClosureID = cl.ID;
                            Db.Closures.Add(cl);
                            Db.AcikHesapHareketleri.AddRange(OffDb.AcikHesapHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                            Db.BankaHareketleri.AddRange(OffDb.BankaHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                            Db.CariTahsilatHareketleri.AddRange(OffDb.CariTahsilatHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                            Db.MasrafFaturalari.AddRange(OffDb.MasrafFaturalari.Where(x => x.ClosureID == cl.ID).ToList());
                            Db.MasrafHareketleri.AddRange(OffDb.MasrafHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                            Db.NakitDetaylari.AddRange(OffDb.NakitDetaylari.Where(x => x.ClosureID == cl.ID).ToList());
                            Db.ZRaporlari.AddRange(OffDb.ZRaporlari.Where(x => x.ClosureID == cl.ID).ToList());
                        }
                        else
                        {
                            ClosureID = new Random().Next(1, int.MaxValue) * -1;
                        }
                    }
                }
            }
            catch (Exception)
            {
                var cl = OffDb.Closures.Where(x => x.KasaID == kasa.ID && x.KasiyerID == kasiyer.ID && x.Tarih == tarih).FirstOrDefault();
                if (cl != null)
                {
                    ClosureID = cl.ID;
                    Db.Closures.Add(cl);
                    Db.AcikHesapHareketleri.AddRange(OffDb.AcikHesapHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                    Db.BankaHareketleri.AddRange(OffDb.BankaHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                    Db.CariTahsilatHareketleri.AddRange(OffDb.CariTahsilatHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                    Db.MasrafFaturalari.AddRange(OffDb.MasrafFaturalari.Where(x => x.ClosureID == cl.ID).ToList());
                    Db.MasrafHareketleri.AddRange(OffDb.MasrafHareketleri.Where(x => x.ClosureID == cl.ID).ToList());
                    Db.NakitDetaylari.AddRange(OffDb.NakitDetaylari.Where(x => x.ClosureID == cl.ID).ToList());
                    Db.ZRaporlari.AddRange(OffDb.ZRaporlari.Where(x => x.ClosureID == cl.ID).ToList());
                }
                else
                {
                    ClosureID = new Random().Next(1, int.MaxValue) * -1;
                }
            }
            return Db;
        }

        private void btnRaporEkle_Click(object sender, EventArgs e)
        {
            DataTable dt = gridZraporlari.DataSource as DataTable;
            dt.Rows.Add(Cevir.Parse<int>(txtZno.Text), Cevir.Parse<double>(txtZTutari.Text), Cevir.Parse<int>(txtFisAdedi.Text), Cevir.Parse<double>(txtFaturaTutari.Text), Cevir.Parse<int>(txtFaturaAdedi.Text), Cevir.Parse<double>(txtIadeTutari.Text), Cevir.Parse<int>(txtIadeAdedi.Text), Cevir.Parse<double>(txtIndirim.Text));
            txtFaturaAdedi.Text = "";
            txtFisAdedi.Text = "";
            txtIadeAdedi.Text = "";
            txtFaturaTutari.Text = "";
            txtIadeTutari.Text = "";
            txtZno.Text = "";
            txtZTutari.Text = "";
            txtIndirim.Text = "";

            double tutar = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                tutar += Cevir.Parse<double>(dt.Rows[i][1]) + Cevir.Parse<double>(dt.Rows[i][3]);
            }
            txtZraporlarToplami.Text = tutar.ToString("n2");
        }

        private void btnRaporSil_Click(object sender, EventArgs e)
        {
            int index = -1;
            if (gridZraporlari.CurrentRow != null && gridZraporlari.CurrentRow.Index > -1)
            {
                index = gridZraporlari.CurrentRow.Index;
            }
            if (index > -1)
            {
                gridZraporlari.Rows.RemoveAt(index);
                gridZraporlari.Refresh();
            }

            DataTable dt = gridZraporlari.DataSource as DataTable;
            double tutar = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                tutar += Cevir.Parse<double>(dt.Rows[i][1]) + Cevir.Parse<double>(dt.Rows[i][3]);
            }
            txtZraporlarToplami.Text = tutar.ToString("n2");
        }

        private void cmbKasiyer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbKasa.SelectedIndex > -1 && cmbKasiyer.SelectedIndex > -1)
            {
                Database db = ReadData();
                NakitDetaylariYukle(db);
                BankaHareketleriYukle(db);
                AcikHesapHareketleriYukle(db);
                MasrafHareketleriYukle(db);
                CariHesapTahsilatlariYukle(db);
                MasrafFaturalariYukle(db);
                ZraporHareketYukle(db);
            }
        }

        /// <summary>
        /// yeni bir database oluşturur ve sql'e kayıt için gönderir
        /// </summary>
        private void Hesapla(bool yazdir)
        {
            Database db = new Database();
            db.Bankalar.AddRange(OffDb.Bankalar.ToArray());

            DataTable dt = gridNakitDetay.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                db.NakitDetaylari.Add(new NakitHareketi()
                {
                    ClosureID = ClosureID,
                    ParaCinsi = Cevir.Parse<string>(dt.Rows[i][0]),
                    Miktar = Cevir.Parse<int>(dt.Rows[i][2]),
                    Tutar = Cevir.Parse<double>(dt.Rows[i][3])
                });
            }

            dt = gridKrediDetay.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Cevir.Parse<double>(dt.Rows[i][2]) > 0)
                {
                    db.BankaHareketleri.Add(new BankaHareketi()
                    {
                        ClosureID = ClosureID,
                        BankaID = Cevir.Parse<int>(dt.Rows[i][0]),
                        Tutar = Cevir.Parse<double>(dt.Rows[i][2]),
                        Slip = Cevir.Parse<int>(dt.Rows[i][3])
                    });
                }
            }


            double indTutari = 0;
            for (int i = 0; i < gridZraporlari.Rows.Count; i++)
            {
                if (gridZraporlari[0, i].Value != null && !string.IsNullOrEmpty(gridZraporlari[0, i].Value.ToString()))
                {
                    indTutari += Cevir.Parse<double>(gridZraporlari[7, i].Value);
                }
            }

            double yemekceki = (from b in db.Bankalar
                                join h in db.BankaHareketleri on b.ID equals h.BankaID
                                where b.BankaTipi == 1
                                select h.Tutar).Sum();

            txtIndirimFarki.Text = (yemekceki - indTutari).ToString("n2");

            if (indTutari > yemekceki)
            {
                DialogResult rs = MessageBox.Show("Yemek çekleri ile indirim tutarları arasında fark var devam etmek isterminiz ?", "Uyarı", MessageBoxButtons.YesNo);
                if (rs == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }



            dt = gridAcikHesap.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Cevir.Parse<double>(dt.Rows[i][1]) > 0)
                {
                    db.AcikHesapHareketleri.Add(new AcikHesapHareketi()
                    {
                        ClosureID = ClosureID,
                        CariID = Cevir.Parse<int>(dt.Rows[i][0]),
                        KdvDahilTutar = Cevir.Parse<double>(dt.Rows[i][1]),
                        KdvHaricTutar = Cevir.Parse<double>(dt.Rows[i][2]),
                        BelgeNo = Cevir.Parse<string>(dt.Rows[i][3])
                    });
                }
            }

            dt = gridHarcamalar.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Cevir.Parse<double>(dt.Rows[i][1]) > 0)
                {
                    db.MasrafHareketleri.Add(new MasrafHareketi()
                    {
                        ClosureID = ClosureID,
                        Aciklama = dt.Rows[i][0].ToString(),
                        Tutar = Cevir.Parse<double>(dt.Rows[i][1])
                    });
                }
            }

            dt = gridZraporlari.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                db.ZRaporlari.Add(new ZRaporu()
                {
                    ClosureID = ClosureID,
                    ZNo = dt.Rows[i][0].ToString(),
                    ZTutari = Cevir.Parse<double>(dt.Rows[i][1]),
                    FisAdedi = Cevir.Parse<int>(dt.Rows[i][2]),
                    FaturaTutari = Cevir.Parse<double>(dt.Rows[i][3]),
                    FaturaAdedi = Cevir.Parse<int>(dt.Rows[i][4]),
                    IadeTutari = Cevir.Parse<double>(dt.Rows[i][5]),
                    IadeAdedi = Cevir.Parse<int>(dt.Rows[i][6]),
                    IndirimTutari = Cevir.Parse<double>(dt.Rows[i][7]),
                });
            }

            dt = gridCariTahsilat.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Cevir.Parse<double>(dt.Rows[i][3]) > 0)
                {
                    db.CariTahsilatHareketleri.Add(new CariTahsilatHareketi()
                    {
                        ClosureID = ClosureID,
                        CariID = Cevir.Parse<int>(dt.Rows[i][0]),
                        Tip = Cevir.Parse<int>(dt.Rows[i][1]),
                        BankaID = Cevir.Parse<int>(dt.Rows[i][2]),
                        Tutar = Cevir.Parse<double>(dt.Rows[i][3]),
                        CekNo = dt.Rows[i][4].ToString()
                    });
                }
            }


            dt = grdMasrafFaturalari.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Cevir.Parse<double>(dt.Rows[i][1]) > 0)
                    db.MasrafFaturalari.Add(new MasrafFatura()
                    {
                        ClosureID = ClosureID,
                        CariID = Cevir.Parse<int>(dt.Rows[i][0]),
                        MasrafID = Cevir.Parse<int>(dt.Rows[i][1]),
                        Tarih = IslemTarihi.ToSmallDate(),
                        Miktar = Cevir.Parse<double>(dt.Rows[i][2]),
                        Tutar = Cevir.Parse<double>(dt.Rows[i][3]),
                        Fiyat = (Cevir.Parse<double>(dt.Rows[i][3]) / Cevir.Parse<double>(dt.Rows[i][2])).Duzelt(3),
                        MagazaNo = MagazaNo.ToInt(),
                        BelgeNo = ""

                    });
            }


            Kasa kasa = (Kasa)cmbKasa.SelectedItem;
            Kasiyer kasiyer = (Kasiyer)cmbKasiyer.SelectedItem;
            KasaKapanisi cl = new KasaKapanisi();
            cl.AcikHesapToplam = db.AcikHesapHareketleri.Select(x => x.KdvDahilTutar).Sum();
            cl.HarcamalarToplam = db.MasrafHareketleri.Select(x => x.Tutar).Sum();
            cl.FaturaToplam = db.ZRaporlari.Select(x => x.FaturaTutari).Sum();
            cl.IadeToplam = db.ZRaporlari.Select(x => x.IadeTutari).Sum();
            cl.ID = ClosureID;
            cl.KasaID = kasa.ID;
            cl.KasiyerID = kasiyer.ID;
            cl.KrediToplam = (from b in db.Bankalar
                              join h in db.BankaHareketleri on b.ID equals h.BankaID
                              where b.BankaTipi == 0
                              select h.Tutar).Sum();

            cl.MagazaID = Cevir.Parse<int>(MagazaNo);
            cl.NakitToplam = db.NakitDetaylari.Select(x => x.Tutar).Sum();
            cl.Tarih = IslemTarihi.ToSmallDate();
            cl.ZRaporToplam = db.ZRaporlari.Select(x => x.ZTutari).Sum();
            cl.TahsilatlarToplam = db.CariTahsilatHareketleri.Select(x => x.Tutar).Sum();
            cl.MasrafFaturalarToplam = db.MasrafFaturalari.Select(x => x.Tutar).Sum();

            txtCariHesapToplam.Text = db.AcikHesapHareketleri.Select(x => x.KdvDahilTutar).Sum().ToString("n2");
            cl.KasaFarki = ((cl.NakitToplam + cl.KrediToplam + Cevir.Parse<double>(txtCariHesapToplam.Text) + cl.HarcamalarToplam + cl.MasrafFaturalarToplam - db.CariTahsilatHareketleri.Select(x => x.Tutar).Sum()) - (cl.ZRaporToplam + cl.FaturaToplam - cl.IadeToplam));

            if (cl.KasaFarki > 0)
            {
                label14.Text = "Kasa Fazlası :";
            }
            else
            {
                label14.Text = "Kasa Noksanı :";
            }

            txtKrediKartiToplam.Text = cl.KrediToplam.ToString("n2"); //db.BankaHareketleri.Select(x => x.Tutar).Sum().ToString("n2");
            txtNakitToplam.Text = db.NakitDetaylari.Select(x => x.Tutar).Sum().ToString("n2");
            txtDigerOdemeler.Text = db.MasrafHareketleri.Select(x => x.Tutar).Sum().ToString("n2");
            txtTahsilatToplam.Text = db.CariTahsilatHareketleri.Select(x => x.Tutar).Sum().ToString("n2");
            txtKasaFarki.Text = cl.KasaFarki.ToString("n2");


            db.Closures.Add(cl);

            if (!yazdir && !Kaydedilmis(db))
                SaveData(db);

            if (yazdir)
            {
                db.Kasiyerler = OffDb.Kasiyerler;
                db.Kasalar = OffDb.Kasalar;
                db.Bankalar = OffDb.Bankalar;
                db.MasrafKartlari = OffDb.MasrafKartlari;
                Yazdir(db);
            }
        }

        private void DeleteData()
        {
            using (KasaEntity ent = new KasaEntity())
            {
                KasaKapanisi cl = ent.KasaKapanislari.Where(x => x.ID == ClosureID).FirstOrDefault();

                var lst = ent.ZRaporlari.Where(x => x.ClosureID == cl.ID).ToList();
                foreach (var item in lst)
                {
                    ent.DeleteObject(item);
                }
                foreach (var item in ent.NakitHareketleri.Where(x => x.ClosureID == cl.ID))
                {
                    ent.DeleteObject(item);
                }
                foreach (var item in ent.BankaHareketleri.Where(x => x.ClosureID == cl.ID))
                {
                    ent.DeleteObject(item);
                }
                foreach (var item in ent.AcikHesapHareketleri.Where(x => x.ClosureID == cl.ID))
                {
                    ent.DeleteObject(item);
                }
                foreach (var item in ent.MasrafHareketleri.Where(x => x.ClosureID == cl.ID))
                {
                    ent.DeleteObject(item);
                }
                foreach (var item in ent.CariTahsilatHareketleri.Where(x => x.ClosureID == cl.ID))
                {
                    ent.DeleteObject(item);
                }
                foreach (var item in ent.MasrafFaturalari.Where(x => x.ClosureID == cl.ID))
                {
                    ent.DeleteObject(item);
                }

                if (cl != null)
                {
                    ent.DeleteObject(cl);
                }
                ent.SaveChanges();
            }
        }

        /// <summary>
        /// Sql servere kayıt yapmaya çalışır olmaz ise offline db ye yazar açılışta da ordan sqle bağlanırsa gönderilir.
        /// </summary>
        /// <param name="db"></param>
        private void SaveData(Database db)
        {
            try
            {
                #region Sql Server Kayıt
                using (KasaEntity ent = new KasaEntity())
                {
                    foreach (var c in db.Closures.Where(x => x.ID == ClosureID))
                    {
                        KasaKapanisi cl = ent.KasaKapanislari.Where(x => x.KasaID == c.KasaID && x.KasiyerID == c.KasiyerID && x.MagazaID == c.MagazaID && x.Tarih == c.Tarih).FirstOrDefault();
                        if (cl != null)
                        {
                            cl.KasaFarki = c.KasaFarki;
                            cl.AcikHesapToplam = c.AcikHesapToplam;
                            cl.HarcamalarToplam = c.HarcamalarToplam;
                            cl.FaturaToplam = c.FaturaToplam;
                            cl.IadeToplam = c.IadeToplam;
                            cl.KrediToplam = c.KrediToplam;
                            cl.NakitToplam = c.NakitToplam;
                            cl.ZRaporToplam = c.ZRaporToplam;
                            cl.TahsilatlarToplam = c.TahsilatlarToplam;
                            cl.MasrafFaturalarToplam = c.MasrafFaturalarToplam;
                        }
                        else
                        {
                            KasaKapanisi cls = new KasaKapanisi()
                            {
                                KasaFarki = c.KasaFarki,
                                AcikHesapToplam = c.AcikHesapToplam,
                                HarcamalarToplam = c.HarcamalarToplam,
                                FaturaToplam = c.FaturaToplam,
                                IadeToplam = c.IadeToplam,
                                KasaID = c.KasaID,
                                KasiyerID = c.KasiyerID,
                                KrediToplam = c.KrediToplam,
                                MagazaID = c.MagazaID,
                                NakitToplam = c.NakitToplam,
                                ZRaporToplam = c.ZRaporToplam,
                                Tarih = new DateTime(c.Tarih.Year, c.Tarih.Month, c.Tarih.Day),
                                TahsilatlarToplam = c.TahsilatlarToplam,
                                MasrafFaturalarToplam = c.MasrafFaturalarToplam
                            };
                            ent.AddToKasaKapanislari(cls);
                        }

                        ent.SaveChanges();
                        DateTime trh = new DateTime(c.Tarih.Year, c.Tarih.Month, c.Tarih.Day);
                        cl = ent.KasaKapanislari.Where(x => x.KasaID == c.KasaID && x.KasiyerID == c.KasiyerID && x.MagazaID == c.MagazaID && x.Tarih == trh).FirstOrDefault();

                        //sil satırları
                        var lst = ent.ZRaporlari.Where(x => x.ClosureID == cl.ID).ToList();
                        foreach (var item in lst)
                        {
                            ent.DeleteObject(item);
                        }
                        foreach (var item in ent.NakitHareketleri.Where(x => x.ClosureID == cl.ID))
                        {
                            ent.DeleteObject(item);
                        }
                        foreach (var item in ent.BankaHareketleri.Where(x => x.ClosureID == cl.ID))
                        {
                            ent.DeleteObject(item);
                        }
                        foreach (var item in ent.AcikHesapHareketleri.Where(x => x.ClosureID == cl.ID))
                        {
                            ent.DeleteObject(item);
                        }
                        foreach (var item in ent.MasrafHareketleri.Where(x => x.ClosureID == cl.ID))
                        {
                            ent.DeleteObject(item);
                        }
                        foreach (var item in ent.CariTahsilatHareketleri.Where(x => x.ClosureID == cl.ID))
                        {
                            ent.DeleteObject(item);
                        }
                        foreach (var item in ent.MasrafFaturalari.Where(x => x.ClosureID == cl.ID))
                        {
                            ent.DeleteObject(item);
                        }

                        foreach (var z in db.ZRaporlari.Where(x => x.ClosureID == c.ID))
                        {
                            ZRaporu rpr = new ZRaporu();
                            rpr.FaturaAdedi = z.FaturaAdedi;
                            rpr.FaturaTutari = z.FaturaTutari;
                            rpr.FisAdedi = z.FisAdedi;
                            rpr.IadeAdedi = z.IadeAdedi;
                            rpr.IadeTutari = z.IadeTutari;
                            rpr.ZNo = z.ZNo;
                            rpr.ZTutari = z.ZTutari;
                            rpr.ClosureID = cl.ID;
                            ent.AddToZRaporlari(rpr);
                        }

                        foreach (var n in db.NakitDetaylari.Where(x => x.ClosureID == c.ID))
                        {
                            NakitHareketi hr = new NakitHareketi();
                            hr.Miktar = n.Miktar;
                            hr.ParaCinsi = n.ParaCinsi;
                            hr.Tutar = n.Tutar;
                            hr.ClosureID = cl.ID;
                            ent.AddToNakitHareketleri(hr);
                        }

                        foreach (var b in db.BankaHareketleri.Where(x => x.ClosureID == c.ID))
                        {
                            BankaHareketi bh = new BankaHareketi();
                            bh.BankaID = b.BankaID;
                            bh.ClosureID = cl.ID;
                            bh.Tutar = b.Tutar;
                            bh.Slip = b.Slip;
                            ent.AddToBankaHareketleri(bh);
                        }

                        foreach (var a in db.AcikHesapHareketleri.Where(x => x.ClosureID == c.ID))
                        {
                            AcikHesapHareketi ac = new AcikHesapHareketi();
                            ac.CariID = a.CariID;
                            ac.ClosureID = cl.ID;
                            ac.KdvDahilTutar = a.KdvDahilTutar;
                            ac.KdvHaricTutar = a.KdvHaricTutar;
                            ac.BelgeNo = a.BelgeNo;
                            ent.AddToAcikHesapHareketleri(ac);
                        }

                        foreach (var h in db.MasrafHareketleri.Where(x => x.ClosureID == c.ID))
                        {
                            MasrafHareketi ms = new MasrafHareketi();
                            ms.Aciklama = h.Aciklama;
                            ms.ClosureID = cl.ID;
                            ms.Tutar = h.Tutar;
                            ent.AddToMasrafHareketleri(ms);
                        }

                        foreach (var ct in db.CariTahsilatHareketleri.Where(x => x.ClosureID == c.ID))
                        {
                            CariTahsilatHareketi ch = new CariTahsilatHareketi();
                            ch.BankaID = ct.BankaID;
                            ch.CariID = ct.CariID;
                            ch.Tip = ct.Tip;
                            ch.CekNo = ct.CekNo;
                            ch.ClosureID = cl.ID;
                            ch.Tutar = ct.Tutar;
                            ent.AddToCariTahsilatHareketleri(ch);
                        }

                        foreach (var dt in db.MasrafFaturalari.Where(x => x.ClosureID == c.ID))
                        {
                            MasrafFatura mf = new MasrafFatura();
                            mf.BelgeNo = dt.BelgeNo;
                            mf.CariID = dt.CariID;
                            mf.ClosureID = cl.ID;
                            mf.Fiyat = dt.Fiyat;
                            mf.MagazaNo = dt.MagazaNo;
                            mf.MasrafID = dt.MasrafID;
                            mf.Miktar = dt.Miktar;
                            mf.Tarih = dt.Tarih;
                            mf.Tutar = dt.Tutar;
                            ent.AddToMasrafFaturalari(mf);
                        }

                        ent.SaveChanges();
                    }
                }
                #endregion
            }
            catch (Exception)
            {
                OffDb.Closures.AddRange(db.Closures);
                OffDb.AcikHesapHareketleri.AddRange(db.AcikHesapHareketleri);
                OffDb.BankaHareketleri.AddRange(db.BankaHareketleri);
                OffDb.CariTahsilatHareketleri.AddRange(db.CariTahsilatHareketleri);
                OffDb.MasrafFaturalari.AddRange(db.MasrafFaturalari);
                OffDb.MasrafHareketleri.AddRange(db.MasrafHareketleri);
                OffDb.NakitDetaylari.AddRange(db.NakitDetaylari);
                OffDb.ZRaporlari.AddRange(db.ZRaporlari);
            }
        }

        private bool Kaydedilmis(Database db)
        {
            bool sonuc;
            if (!Program.AdminMode)
            {
                using (KasaEntity ent = new KasaEntity())
                {
                    var c = db.Closures.Where(x => x.ID == ClosureID).FirstOrDefault();
                    KasaKapanisi cl = ent.KasaKapanislari.Where(x => x.KasaID == c.KasaID && x.KasiyerID == c.KasiyerID && x.MagazaID == c.MagazaID && x.Tarih == c.Tarih).FirstOrDefault();
                    if (cl != null)
                        sonuc = true;
                    else
                        sonuc = false;
                }
            }
            else
            {
                sonuc = false;
            }
            return sonuc;
        }

        private bool Kontrol(int kasaID, int kasiyerID, int magazaNo, DateTime tarih)
        {
            bool sonuc;
            using (KasaEntity ent = new KasaEntity())
            {
                KasaKapanisi cl = ent.KasaKapanislari.Where(x => x.KasaID == kasaID && x.KasiyerID == kasiyerID && x.MagazaID == magazaNo && x.Tarih == tarih).FirstOrDefault();
                if (cl != null)
                    sonuc = true;
                else
                    sonuc = false;
            }
            return sonuc;
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            bool var = false;
            for (int i = 0; i < gridZraporlari.Rows.Count; i++)
            {
                if (gridZraporlari[0, i].Value != null && !string.IsNullOrEmpty(gridZraporlari[0, i].Value.ToString()))
                {
                    var = true;
                    break;
                }
            }

            if (!var)
            {
                MessageBox.Show("Hiç Z Raporu eklememişsiniz !");
            }
            else
            {
                Hesapla(false);
            }
        }

        private void gridNakitDetay_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 1)
            {
                if (gridNakitDetay[1, e.RowIndex] != null)
                {
                    gridNakitDetay[3, e.RowIndex].Value = (Cevir.Parse<double>(gridNakitDetay[1, e.RowIndex].Value) * Cevir.Parse<double>(gridNakitDetay[2, e.RowIndex].Value));
                }
            }
            gridNakitDetay.Refresh();
        }

        private void Yazdir(Database db)
        {
            try
            {
                using (FastReport.Report report = Printing.GetReport(ReportTypeOption.KasiyerRaporu))
                {
                    CashReport rp = new CashReport();
                    var banka = (from h in db.BankaHareketleri
                                 join b in db.Bankalar on h.BankaID equals b.ID
                                 where b.BankaTipi == 0
                                 select h);


                    rp.BankaToplam = banka.Select(x => x.Tutar).Sum(); //db.BankaHareketleri.Select(x => x.Tutar).Sum();

                    int kasaid = db.Closures.Select(x => x.KasaID).FirstOrDefault();
                    int kasiyerid = db.Closures.Select(x => x.KasiyerID).FirstOrDefault();

                    rp.KasaNo = db.Kasalar.Where(x => x.ID == kasaid).Select(x => x.No).FirstOrDefault();
                    rp.KasiyerAdi = db.Kasiyerler.Where(x => x.ID == kasiyerid).Select(x => x.KasiyerAdi).FirstOrDefault();
                    rp.NakitToplam = db.NakitDetaylari.Select(x => x.Tutar).Sum();
                    rp.Ztoplam = db.ZRaporlari.Select(x => x.ZTutari + x.FaturaTutari).Sum();
                    KasaKapanisi cl = db.Closures.FirstOrDefault();
                    rp.Fark = cl.KasaFarki;
                    rp.GerceklesenToplam = (cl.NakitToplam + cl.KrediToplam + db.AcikHesapHareketleri.Select(x => x.KdvDahilTutar).Sum() + cl.HarcamalarToplam + cl.MasrafFaturalarToplam + db.CariTahsilatHareketleri.Select(x => x.Tutar).Sum());

                    Array.ForEach(db.MasrafHareketleri.Select(x => new HarcamaBilgileri { Adi = x.Aciklama, Tutar = x.Tutar }).ToArray(), rp.HarcamaBilgileri.Add);
                    Array.ForEach((from mh in db.MasrafFaturalari join m in db.MasrafKartlari on mh.MasrafID equals m.ID group mh by m.Adi into g select new HarcamaBilgileri { Adi = g.Key, Tutar = g.Sum(x => x.Tutar) }).ToArray(), rp.MasrafFaturalari.Add);
                    Array.ForEach(db.NakitDetaylari.Select(x => new NakitBilgileri { Miktar = x.Miktar, ParaCinsi = x.ParaCinsi, Tutar = x.Tutar }).ToArray(), rp.NakitBilgileri.Add);

                    var ary = (from b in db.Bankalar join h in db.BankaHareketleri on b.ID equals h.BankaID select new BankaBilgileri { Adi = b.Aciklama, Miktar = h.Slip, Tutar = h.Tutar }).ToArray();
                    Array.ForEach(ary, rp.BankaBilgileri.Add);

                    System.Windows.Forms.BindingSource binding = new System.Windows.Forms.BindingSource { DataSource = rp };
                    report.RegisterData(binding, "Report", 10);
                    report.GetDataSource("Report").Enabled = true;
                    report.Prepare();
                    report.Print();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Yazdırma İptal Edildi");
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (new frmSifre().ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                CashReport rp = new CashReport();
                using (FastReport.Report report = Printing.GetReport(ReportTypeOption.KasiyerRaporu))
                {
                    System.Windows.Forms.BindingSource binding = new System.Windows.Forms.BindingSource { DataSource = rp };
                    report.RegisterData(binding, "Report", 10);
                    report.GetDataSource("Report").Enabled = true;
                    report.Prepare();
                    report.Design();

                    using (KasaEntity ent = new KasaEntity())
                    {
                        BelgeSablonu belge = (from b in ent.BelgeSablonlari where b.ReportType == (byte)ReportTypeOption.KasiyerRaporu select b).FirstOrDefault();
                        if (belge == null)
                        {
                            ent.AddToBelgeSablonlari(new BelgeSablonu()
                            {
                                ReportType = (byte)ReportTypeOption.KasiyerRaporu,
                                TemplateContent = File.ReadAllBytes(Printing.GetPath(ReportTypeOption.KasiyerRaporu))
                            });
                        }
                        else
                        {
                            belge.ReportType = (byte)ReportTypeOption.KasiyerRaporu;
                            belge.TemplateContent = File.ReadAllBytes(Printing.GetPath(ReportTypeOption.KasiyerRaporu));
                        }
                        ent.SaveChanges();
                    }
                }
            }
        }

        private void printToolStripButton_Click(object sender, EventArgs e)
        {
            if (cmbKasa.SelectedIndex > -1 && cmbKasiyer.SelectedIndex > -1)
            {
                Kasa kasa = (Kasa)cmbKasa.SelectedItem;
                Kasiyer kasiyer = (Kasiyer)cmbKasiyer.SelectedItem;
                if (Kontrol(kasa.ID, kasiyer.ID, Cevir.Parse<int>(MagazaNo), IslemTarihi.ToSmallDate()))
                {
                    Hesapla(true);
                }
                else
                {
                    MessageBox.Show("Kaydetmeden yazdırılamaz !");
                }
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            DeleteData();
            this.Close();
        }
    }
}

